<template>
  <div class="page-audit-sell">
    <base-info class="base-info" categoryTitle="基本信息" :params="baseInfoParams" :data="data" :widthPercent="widthPercent">
    </base-info>
    <div class="goods-title">货物明细</div>
    <egrid class="egrid-class" border
           :header-cell-style="getHeaderCellClass"
           :data="data.wmsArDetailGoodsVoList"
           :columns="goodsColumns"
           propSpan="wrId"
           :columns-schema="columnsSchema"
           :columns-props="columnsProps">
    </egrid>

    <div class="goods-title">交易信息</div>
    <el-form :inline="true" :model="auditForm" ref="auditForm">
      <div class="trade-date">
        <el-form-item :label="datelabel" prop="sellDate">
          <el-date-picker class="block"
                          v-model="auditForm.tradeDate"
                          type="date"
                          :placeholder="tradePlaceholder"
                          value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="tradeType === '1'" label="最晚回购日期" prop="repurchaseLastDate">
          <el-date-picker class="block"
                          v-model="auditForm.repurchaseLastDate"
                          type="date"
                          placeholder="选择最晚回购日期"
                          value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="tradeType === '1'">
          <div class="text-class">货物期望回购期限：<span>{{data.repurchaseDays}}</span></div>
        </el-form-item>
      </div>
    </el-form>
    <egrid border
           show-summary
           sum-text="合计"
           :summary-method="getSummaries"
           :header-cell-style="getHeaderCellClass"
           :data="data.wmsArDetailGoodsVoList"
           :columns="tradeColumns"
           :columns-schema="columnsSchema"
           :columns-props="columnsProps">
    </egrid>
    <div style="margin-top: 20px">
      <input-com :headTitle="'审核说明(选填)'" :inputValue="auditForm.applyDesc" @getInputVal="getInputVal"
                 :headSonTitle="'填写审核说明'"></input-com>
      <el-row class="btnFrameClass">
        <el-button v-permission="['wms:trade:buyback:audit:pass']" class="singleBtnClass" type="primary" @click="auditTrade('auditForm', 1)">审核通过</el-button>
        <el-button v-permission="['wms:trade:buyback:audit:refuse']" class="singleBtnClass" type="primary" plain @click="auditTrade('auditForm', 2)">审核不通过</el-button>
      </el-row>
    </div>
    <pc-dialog :is-show="showBillDetailDialog" title='仓单详情' @on-close="showBillDetailDialog = false">
      <detail :id="wrId"></detail>
    </pc-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
  import PcDialog from 'components/dialog';
  import BaseInfo from 'components/wms/comm/BaseInfo';
  import inputCom from 'components/input/baseTitleInput';
  import Detail from 'src/views/wms/dataquery/billlist/billManagement/billDetail.vue';
  import mValidate from 'utils/common-method/validate/index';
  let that;
  // 操作按钮
  var Btn = {
    template: `<div style="text-align: center">
        <el-button type="primary" plain @click="viewdetail(row)">查看</el-button>
      </div>`,
    props: ['row'],
    computed: {},
    methods: {
      // 查看仓单详情
      viewdetail(val) {
        this.$emit('view-detail', val);
      }
    }
  };

  var Editor = {
    template: `<div style="text-align: center">
           <el-input maxlength="10" type="text"
           @keyup.native="verifyDecimal(row, column)"
           @blur="convertToNumber(row, column)"
           v-model="row[column.property]" ></el-input>
     </div>`,
    props: ['row', 'column'],
    computed: {},
    methods: {
      // 控制职能输入数字和小数点
      verifyDecimal(row, column) {
        this.$emit('verify-decimal', row, column);
      },
      // 将数字字符串转换成数字
      convertToNumber(row, column) {
        this.$emit('convert-to-number', row, column);
      }
    }
  };
  export default{
    props: {
      id: [String, Number], // 业务ID
      tradeType: [String, Number], // 交易类型
      baseInfoProp: Array, // 基本信息增加的显示信息
      goodsInfoPropParams: Array, // 货物信息展示不同列的参数
      tradeInfoPropParams: Array, // 交易信息展示不同列的参数
      widthPercent: String // 基本信息中的一项占一行的宽度（如： 25%）
    },
    components: {BaseInfo, PcDialog, inputCom, Detail},
    data() {
      return {
        baseParams: [
          {
            label: '出售方',
            labelIcon: ['icon maliiconfont maliicon-img_details_custodia'],
            delimiter: ' ',
            key: 'sellerName'
            /*            baseClass: ['base-single'], // 子组件的基本样式
             labelClass: ['label-class'], // 标签的样式
             valueClass: ['value-class'] // 内容样式 */
          },
          {
            label: '交易对象',
            labelIcon: ['icon maliiconfont maliicon-img_detailse_refund'],
            delimiter: ' ',
            key: 'buyerName'
          },
          {
            label: '保管人',
            labelIcon: ['icon maliiconfont maliicon-storehouse'],
            key: 'storageCompanyName',
            delimiter: ' '
          },
          {
            label: '保管仓',
            labelIcon: ['icon maliiconfont maliicon-img_details_allocati'],
            delimiter: ' ',
            key: 'storageName'
          },
          {
            label: '申请人',
            labelIcon: ['icon maliiconfont maliicon-img_details_figure'],
            delimiter: ' ',
            key: 'creator'
          },
          {
            label: '申请时间',
            labelIcon: ['icon maliiconfont maliicon-img_details_calendar'],
            delimiter: ' ',
            key: 'createdTime'
          }
        ],
        auditForm: {
          id: null, // 主键id
          sellArNo: null, // 出售申请编号
          auditType: null, // 审核类型(1:通过 2:不通过)
          arType: 1, // 交易类型(1:出售 2:回购)
          applyDesc: null, // 审核说明 varchar(200)
          tradeDate: '', // 交易日期 - 回购填写
          repurchaseDate: '', // 回购日期 - 回购填写
          repurchaseLastDate: null, // 最晚回购日期 - 出售填写
          sellDate: null, // 出售日期 - 出售填写
          version: null, // 版本号
          wmsArAuditGoodsDtoList: null // 审核出售/回购-货物信息
        },
        data: {},
        columnsSchema: {
          '生产厂家': { minWidth: 100 },
          '包装': { minWidth: 100 },
          '出售数量': { minWidth: 100 },
          '单位': { minWidth: 100 },
          '生产日期': { minWidth: 100 },
          '回购数量': { minWidth: 100 },
          '对应仓单': { fixed: 'right' },
          '抄码重量（kg）': {
            minWidth: 150,
            fixed: 'right',
            component: Editor, // 'el-input'
            listeners: {
              'verify-decimal' (row, column) {
                mValidate.verifyDecimal(row, column.property);
              },
              'convert-to-number' (row, column) {
                row[column.property] = mValidate.convertToNumber(row[column.property]);
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          },
          '交易金额（元）': {
            minWidth: 150,
            fixed: 'right',
            component: Editor, // 'el-input'
            listeners: {
              'verify-decimal' (row, column) {
                mValidate.verifyDecimal(row, column.property);
              },
              'convert-to-number' (row, column) {
                row[column.property] = mValidate.convertToNumber(row[column.property]);
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          }
        },
        // columnsProps 用于定义所有 columns 公共的属性，
        // 这里属性可以参考这里： http://element.eleme.io/#/zh-CN/component/table#table-column-attributes
        columnsProps: {
          height: 40,
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true
        },
        // 货物信息、交易信息公共列
        baseColumns: [
          {
            label: '仓单业务号',
            prop: 'busNo'
          },
          {
            label: '货物名称',
            prop: 'goodsName'
          },
          {
            label: '柜号',
            prop: 'cntrNo'
          },
          {
            label: '生产厂家',
            prop: 'vendor'
          },
          {
            label: '原产地',
            prop: 'countryOrigin'
          }
        ],
        goodsAdditionalCols: [
          {
            label: '包装',
            prop: 'packageDesc'
          },
          {
            label: '生产日期',
            prop: 'productDate'
          },
          {
            label: '出售数量',
            prop: 'sellNum'
          },
          {
            label: '单位',
            prop: 'unitDesc'
          },
          {
            label: '参考出售重量（kg）',
            prop: 'refTotalWeight'
          },
          {
            label: '对应仓单',
            width: 116,
            merge: true,
            component: Btn, // 'el-button'
            listeners: {
              'view-detail' (data) {
                that.wrId = data.wrId; // 仓单ID
                that.showBillDetailDialog = true;
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          }
        ],
        tradeAdditionalColumns: [
          {
            label: '生产日期',
            prop: 'productDate'
          },
          {
            label: '出售数量',
            prop: 'sellNum'
          },
          {
            label: '参考出售重量（kg）',
            prop: 'refTotalWeight'
          },
          {
            label: '抄码重量（kg）',
            prop: 'scanWeight'
          },
          {
            label: '交易金额（元）',
            prop: 'transactionAmount'
          }
        ],
        spanArr: [],
        tradePlaceholder: '',
        wrId: null, // 仓单ID
        showBillDetailDialog: false // 是否显示仓单详情控制变量
      };
    },
    created() {
      that = this;
      this.initData();
    },
    computed: {
      // 根据交易类型获取交易时间标签
      datelabel() {
        let type = this.tradeType;
        if (typeof this.tradeType === 'string') {
          type = parseInt(this.tradeType);
        }
        if (type === 1) {
          this.tradePlaceholder = '选择出售日期';
          return '出售日期';
        } else {
          this.tradePlaceholder = '选择回购日期';
          return '回购日期';
        }
      },
      // 基本信息列
      baseInfoParams() {
        if (this.baseInfoProp) {
          this.baseParams[0].label = '回购方';
          return this.baseParams.concat(this.baseInfoProp);
        } else {
          return this.baseParams;
        }
      },
      // 货物信息数据列
      goodsColumns() {
        let columns = [].concat(this.baseColumns);
        if (this.goodsInfoPropParams) {
          columns = columns.concat(this.goodsAdditionalCols.slice(0, 4));
          columns = columns.concat(this.goodsInfoPropParams);
          columns = columns.concat(this.goodsAdditionalCols.slice(5, this.goodsAdditionalCols.length));
/*          this.goodsAdditionalCols.splice(4, 1, this.goodsInfoPropParams);
          let columns1 = this.baseColumns.concat(this.goodsAdditionalCols);
          console.log('columns: ' + JSON.stringify(columns));
          console.log('columns1: ' + JSON.stringify(columns1)); */
          return columns;
        } else {
          return columns.concat(this.goodsAdditionalCols);
        }
      },
      // 交易信息数据列
      tradeColumns() {
        let columns = [].concat(this.baseColumns);
        return columns.concat(this.tradeInfoPropParams ? this.tradeInfoPropParams : this.tradeAdditionalColumns);
      }
    },
    methods: {
      // 根据找库订单ID获取找库订单的详细数据
      initData() {
        this.ajax({
          type: 'GET',
          url: '/maliwms/ar/getArDetailByArId?arId=' + this.id,
          loading: true,
          success: (res) => {
            setTimeout(() => {
              this.$pcNProgress.done();
            }, 300);
            if (res.code === 200) {
              this.data = res.result;
            } else {
              this.errorTip(res.message);
            }
          }
        });
      },
      // 备注
      getInputVal(val) {
        this.auditForm.applyDesc = val;
      },
      // 定义表头的样式
      getHeaderCellClass({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0) {
          return 'background: #ffffff; height: 50px';
        } else {
          return '';
        }
      },
      /*
        审核不通过函数
        @param form 表单的名字
        @param auditType 审核类型(1:通过 2:不通过)
       */
      auditTrade(form, auditType) {
        this.auditForm.auditType = auditType;
        this.auditForm.id = this.data.id;
        this.auditForm.sellArNo = this.data.sellArNo; // 出售申请编号
        this.auditForm.arType = this.data.arType; // 交易类型(1:出售 2:回购)
        this.auditForm.version = this.data.version; // 版本号
        this.auditForm.wmsArAuditGoodsDtoList = this.data.wmsArDetailGoodsVoList; // 审核出售/回购-货物信息
        this.$emit('audit-trade', this.auditForm);
      },
      // 计算合计值的函数
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index >= 0 && index < 6 && index !== 1) {
            sums[index] = '';
            return;
          }
          if (index === 1) {
            sums[index] = '合计';
            return;
          }
          // 将表格中的每行数字数据相加
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            // 对小数保留两位有效数字，四舍五入
            sums[index] = Number(sums[index].toFixed(2));
          } else {
          }
        });
        return sums;
      },
      // 查看仓单详情
      viewBillDetail(data) {
        that.wrId = data.wrId;
        that.showBillDetailDialog = true;
      }
    }
  };
</script>
<style>
  .page-audit-sell {
    width: 958px;
  }

  .page-audit-sell .base-info {
    height: auto;
    border-top: 1px solid #e5e5e5;
    border-left: 1px solid #e5e5e5;
    background-color: #f5f6f7
  }
  .page-audit-sell .el-form-item {
    display: inline-block;
    margin-left: 20px;
    margin-right: 20px;
  }
  .page-audit-sell .el-form--inline .el-form-item__content {
    vertical-align: middle !important;
  }
  .page-audit-sell .goods-title {
    padding-left: 20px;
    height: 50px;
    line-height: 50px;
    width: 100%;
    margin-top: 20px;
    border-left: 1px solid #e5e5e5;
    border-right: 1px solid #e5e5e5;
    border-top: 1px solid #e5e5e5;
    background: white
  }
  .page-audit-sell .trade-date {
    height: 50px;
    line-height: 50px;
    width: 100%;
    border-left: 1px solid #e5e5e5;
    border-right: 1px solid #e5e5e5;
    border-top: 1px solid #e5e5e5;
    background: white
  }

  .page-audit-sell .text-div {
    width: 958px;
    height: auto;
    margin-top: 20px;
    padding-bottom: 24px;
    border: 1px solid #e5e5e5;
    background-color: white;
  }

  .page-audit-sell .text-div .text-class {
    margin-top: 20px;
    margin-left: 20px;
    color: #333333;
  }

  .page-audit-sell .maliiconfont {
    color: #ff6c2b;
  }
  .page-audit-sell .btnFrameClass {
    margin-top: 40px;
    margin-bottom: 20px;
    text-align: center;
  }

  .page-audit-sell .singleBtnClass {
    width: 140px;
    height: 40px;
  }
  .page-audit-sell .el-input--small .el-input__inner {
    height: 28px;
    line-height: 28px;
  }
</style>
